import CommonUtil from "./CommonUtil";
import {settings} from "../../app/consts/Settings";

export default class AudioEngine {
    public static readonly instance = new AudioEngine();
    private audioIdPool: { [k: string]: number; } = {};
    private audioClipPool: { [k: string]: cc.AudioClip; } = {};

    // 播放bgm
    public async bgm(path: string) {
        if (!settings.musicOpen) {
            return;
        }
        let clip = this.audioClipPool[path];
        if (!clip) {
            clip = await CommonUtil.loadResNoError<cc.AudioClip>(path);
            this.audioClipPool[path] = clip;
        }
        const state = cc.audioEngine.getState(this.audioIdPool[path]);
        if (this.audioIdPool[path] >= 0 && state > 0) {
            cc.audioEngine.resume(this.audioIdPool[path]);
            return;
        }
        this.audioIdPool[path] = cc.audioEngine.play(clip, true, 1);
    }

    // 播放普通音效.
    public async play(path: string, times: number = 1, loop: boolean = false, volume: number = 1) {
        if (!settings.musicOpen) {
            return;
        }
        let clip = this.audioClipPool[path];
        if (!clip) {
            clip = await CommonUtil.loadResNoError<cc.AudioClip>(path);
            this.audioClipPool[path] = clip;
        }
        if (times <= 1) {
            return new Promise((resolve) => {
                this.audioIdPool[path] = cc.audioEngine.play(clip, loop, volume);
                resolve();
            })
        }
        this.audioIdPool[path] = cc.audioEngine.play(clip, loop, volume);
        let duration = cc.audioEngine.getDuration(this.audioIdPool[path]) + 0.1;
        CommonUtil.schedule(duration, times - 1, () => {
            new Promise((resolve) => {
                this.audioIdPool[path] = cc.audioEngine.play(clip, loop, volume);
                resolve();
            }).catch(() => {
            })
        });
    }

    public pause(path: string) {
        const id = this.audioIdPool[path];
        cc.audioEngine.pause(id);
    }

    public stop(path: string) {
        const id = this.audioIdPool[path];
        cc.audioEngine.stop(id);
    }

    public resume(path: string) {
        const id = this.audioIdPool[path];
        cc.audioEngine.resume(id);
    }

}
export const audioEngine = new AudioEngine();
